﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Runtime.Remoting.Lifetime;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;

namespace Ant
{
    public partial class Form1 : Form
    {
        private PictureBox picPikachu;
        private Point mouseOffset; //记录鼠标位置偏移
        private bool isMouseDown = false; // 记录鼠标是否按下
        private NotifyIcon notifyIcon; // 托盘图标
        private ContextMenuStrip picContextMenu; //皮卡丘右键菜单
        private Process ffmpegProcess; // ffmpeg 进程



        // 请替换为你从讯飞控制台获取的 API 密钥
        private static readonly string apiPassword = "QFpFTNlkIEULpbIjAmOq:kHRxVSgbLMvrlwWQOffp"; // 替换为API密钥
        private static readonly string apiUrl =
            "https://spark-api-open.xf-yun.com/v1/chat/completions";

        public Form1()
        {
            InitializeComponent();

            // 初始化窗体设置
            this.TopMost = true; 
            this.FormBorderStyle = FormBorderStyle.None;
            this.BackColor = Color.Black; 
            this.TransparencyKey = Color.Black; 
            this.StartPosition = FormStartPosition.CenterScreen; 
            this.Width = 300; 
            this.Height = 300; 

            // 初始化皮卡丘图片
            picPikachu = new PictureBox
            {
                Image = Image.FromFile("pk.png"),
                SizeMode = PictureBoxSizeMode.Zoom, 
                Dock = DockStyle.Fill, 
                BackColor = Color.Transparent 
            };
            this.Controls.Add(picPikachu);

            picContextMenu = new ContextMenuStrip();
            picContextMenu.Items.Add("打开网易云音乐", null, OpenNetEaseCloudMusic);
            picContextMenu.Items.Add("打开 CMD", null, OpenCmd);
            picContextMenu.Items.Add("AI对话", null, OpenAIChat);
            picContextMenu.Items.Add("启动jar包", null, OpenAIChat1);
            picContextMenu.Items.Add("截图", null, OpenAIChat2);
            picContextMenu.Items.Add("录屏", null, OpenAIChat3);

            picPikachu.ContextMenuStrip = picContextMenu;

    
            this.picPikachu.MouseDown += MouseDownEvent;
            this.picPikachu.MouseMove += MouseMoveEvent;
            this.picPikachu.MouseUp += MouseUpEvent;

            // 隐藏窗体
            //this.Load += (s, e) => this.Hide();
            //this.Shown += (s, e) => this.Hide(); // 防止首次显示窗口

            // 初始化托盘图标
            notifyIcon = new NotifyIcon
            {
                Icon = GenerateOptimizedIcon("T1.jpg"),
                Visible = true, // 显示图标
                Text = "我的后台助手"
            };


            var contextMenu = new ContextMenuStrip();
            contextMenu.Items.Add("显示小助手", null, ShowMainForm);
            contextMenu.Items.Add("隐藏小助手", null, HideMainForm);
            contextMenu.Items.Add("退出", null, ExitApplication);


            notifyIcon.ContextMenuStrip = contextMenu;

       
            notifyIcon.DoubleClick += ShowMainForm;
        }

        private void OpenAIChat1(object sender, EventArgs e)
        {
            MessageBox.Show("功能正在开发中，敬请期待！");
        }
        private void OpenAIChat2(object sender, EventArgs e)
        {
            MessageBox.Show("功能正在开发中，敬请期待！");

        }
        private void OpenAIChat3(object sender, EventArgs e)
        {
            StartScreenRecording();
        }

        private void StartScreenRecording()
        {
            try
            {
                string ffmpegPath = Path.Combine(Application.StartupPath, "ffmpeg.exe");
                string arguments = $"-f gdigrab -framerate 30 -i desktop {DateTime.Now.ToString("yyyyMMddHHmmss")}.mp4";
                // 设置 ProcessStartInfo 来启动 FFmpeg 录制
                ProcessStartInfo startInfo = new ProcessStartInfo
                {
                    FileName = ffmpegPath,  // ffmpeg.exe 路径
                    Arguments = arguments,  // 录制命令
                    CreateNoWindow = false,  // 不显示命令行窗口
                    UseShellExecute = false // 不使用操作系统的外壳来启动进程
                };

                Process ffmpegProcess = Process.Start(startInfo);
                MessageBox.Show("录屏已开始，按 Ctrl+C 停止录制。");
                // 等待录制结束
                ffmpegProcess.WaitForExit();
                // 提示用户录制已结束
                MessageBox.Show("录屏已结束，文件保存在程序的当前目录下。");

            }catch (Exception ex)
            {
                MessageBox.Show("发生错误：" + ex.Message);
            }
        }

        private async void OpenAIChat(object sender, EventArgs e)
        {
            // 创建并显示AI聊天窗体
            Form2 chatForm = new Form2();
            chatForm.ShowDialog();
        }

        private void OpenCmd(object sender, EventArgs e)
        {
            try
            {
                Process.Start("cmd.exe");
            }
            catch (Exception ex)
            {
                MessageBox.Show("启动CMD失败：" + ex.Message);
            }
        }

        private void OpenNetEaseCloudMusic(object sender, EventArgs e)
        {
            try
            {
                Process.Start("https://music.163.com/");
            }
            catch (Exception ex)
            {
                MessageBox.Show(
                    "打开网易云音乐官网失败: " + ex.Message,
                    "错误",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error
                );
            }
        }

        // 鼠标按下事件
        private void MouseDownEvent(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                isMouseDown = true;
                mouseOffset = new Point(-e.X, -e.Y); // 记录鼠标按下时的偏移
            }
        }

        // 鼠标移动事件
        private void MouseMoveEvent(object sender, MouseEventArgs e)
        {
            if (isMouseDown)
            {
                Point mousePos = Control.MousePosition; // 获取鼠标当前位置
                mousePos.Offset(mouseOffset.X, mouseOffset.Y); // 加上偏移值
                this.Location = mousePos; // 更新窗体位置
            }
        }

        // 鼠标释放事件
        private void MouseUpEvent(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                isMouseDown = false; // 鼠标释放，停止拖动
            }
        }

        // 显示主窗口
        private void ShowMainForm(object sender, EventArgs e)
        {
            this.Show();
            this.WindowState = FormWindowState.Normal; // 恢复窗体
            this.Activate(); // 窗口置顶
        }

        // 隐藏主窗口
        private void HideMainForm(object sender, EventArgs e)
        {
            this.Hide();
        }

        // 退出程序
        private void ExitApplication(object sender, EventArgs e)
        {
            notifyIcon.Visible = false; // 关闭托盘图标
            Application.Exit(); // 退出应用
        }

        // 禁止关闭（重写关闭事件）
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
            {
                e.Cancel = true; // 阻止窗口关闭
                this.Hide(); // 隐藏窗口
            }
            base.OnFormClosing(e);
        }

        private Icon GenerateOptimizedIcon(string filePath)
        {
            // 加载原始图片
            using (Bitmap originalBitmap = new Bitmap(filePath))
            {
                // 确保图片缩放到合适的大小（通常托盘图标 32x32）
                int iconSize = 32; // 定义图标大小
                using (Bitmap resizedBitmap = new Bitmap(iconSize, iconSize))
                {
                    using (Graphics g = Graphics.FromImage(resizedBitmap))
                    {
                        // 设置高质量渲染
                        g.InterpolationMode = System
                            .Drawing
                            .Drawing2D
                            .InterpolationMode
                            .HighQualityBicubic;
                        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                        g.CompositingQuality = System
                            .Drawing
                            .Drawing2D
                            .CompositingQuality
                            .HighQuality;

                        // 填充透明背景
                        g.Clear(Color.Transparent);

                        // 将原始图片按比例缩放绘制到新尺寸
                        g.DrawImage(originalBitmap, new Rectangle(0, 0, iconSize, iconSize));
                    }

                    // 将优化后的 Bitmap 转换为 Icon
                    IntPtr hIcon = resizedBitmap.GetHicon();
                    return Icon.FromHandle(hIcon);
                }
            }
        }
    }
}
